//
//  Controller.m
//  Game of Life
//
//  Created by James Durkee on 5/12/09.
//  Copyright 2009 James and MP. All rights reserved.
//

#import "Controller.h"


@implementation Controller
- (void)awakeFromNib {
	grid = [gridView grid];
	timer = nil;
}

- (IBAction)next:(id)sender {
	[self next];
}

- (void)next {
	[grid nextGeneration];
	[generationLabel setStringValue:[NSString stringWithFormat:@"Gen. %d", [grid generation]]];
	[gridView setNeedsDisplay:YES];
}

- (IBAction)start:(id)sender {
	NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
	
	if ([[controlButton title] isEqualToString:@"Start"]) {
		[self run:YES];
		
		NSLog(@"%@", [runLoop currentMode]);
	} else {
		[self run:NO];
	}
}

- (IBAction)clear:(id)sender {
	[gridView clear];
	
	[self run:NO];
	
	[generationLabel setStringValue:[NSString stringWithFormat:@"Gen. %d", [grid generation]]];
}

- (IBAction)intervalChanged:(id)sender {
	[intervalLabel setStringValue:[NSString stringWithFormat:@"%@ second interval", [interval stringValue]]];
	
	if (![[controlButton title] isEqualToString:@"Start"]) {
		[self run:NO];
		[self run:YES];
	}
}

- (void)run:(BOOL)b {
	NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
	
	if (b) {
		[controlButton setTitle:@"Stop"];
		[controlMenuItem setAttributedTitle:@"Stop"];
		NSLog(@"Starting");
		timer = [[NSTimer timerWithTimeInterval:[interval doubleValue] 
										 target:self 
									   selector:@selector(next) 
									   userInfo:nil 
										repeats:YES] retain];
		
		[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
		[runLoop acceptInputForMode:NSDefaultRunLoopMode beforeDate:nil];
		NSLog(@"%@", [runLoop currentMode]);
	} else {
		[controlButton setTitle:@"Start"];
		[controlMenuItem setAttributedTitle:@"Start"];
		NSLog(@"Stopping");
		
		[timer invalidate];
		[timer release];
		timer = [[NSTimer timerWithTimeInterval:[interval doubleValue] 
										 target:self 
									   selector:@selector(next) 
									   userInfo:nil 
										repeats:YES] retain];
	}
	
}
@end
